﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Collections;
using System.Data;
using System.Data.OleDb;
using System.Windows.Forms;
using System.Runtime.Remoting.Messaging;
using System.Threading;

namespace PIBV
{
    public class PID_BaseClass
    {
        //cache dataset
        protected DataSet ds;

        //connection
        private OleDbConnection _connection = null;

        protected OleDbConnection Connection
        {
            get { return _connection; }
            set { _connection = value; }
        }

        private string _connectionString;

        public string ConnectionString
        {
            get { return _connectionString; }
            set { _connectionString = value; }
        }

        //ctor
        public PID_BaseClass()
        {
            ds = new DataSet();
        }

        public void SetConnection(OleDbConnection conn)
        {
            _connection = conn;
        }

        public Exception ExecuteQuery(string query)
        {
            Exception ex = null;
            try
            {
                OleDbCommand cmd = new OleDbCommand(query, Connection);
                cmd.CommandType = CommandType.Text;
                cmd.ExecuteNonQuery();
            }
            catch (Exception e)
            { ex = e; }
            return ex;
        }

        public object ExecuteScalar(string query)
        {
            object result = null;
            try
            {
                OleDbCommand cmd = new OleDbCommand(query, Connection);
                cmd.CommandType = CommandType.Text;
                result = cmd.ExecuteScalar();
            }
            catch 
            {
            }
            return result;
        }

        public DataSet ExecuteQueryInToDataSet(string query, DataSet dataSet, string tableName, bool bClearTable)
        {
            OleDbCommand cmd = null;
            try
            {
                //Connect();
                //create dataset if it isn't created
                if (dataSet == null)
                    dataSet = new DataSet();

                cmd = new OleDbCommand(query, Connection);
                cmd.CommandType = CommandType.Text;
                OleDbDataAdapter da = new OleDbDataAdapter(cmd);

                //clear table
                if (bClearTable)
                    if (dataSet.Tables.Contains(tableName))
                        dataSet.Tables[tableName].Clear();

                //fill data
                da.Fill(dataSet, tableName);

            }
            catch (Exception ex)
            {
                //Disconnect();
                throw ex;
            }
            finally
            {
                //Disconnect();
            }

            return dataSet;
        }

    }
}
